#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2020/4/22 10:12
# @Author  : Mr. Cui
# @File    : jenkins_api.py
# @Software: PyCharm
import sys
import os

from lxml import etree
from base_server.diyMySql import *
import configparser
from base_server.base_send import *
import os
from .apis import *
import time

class Job_yapi():
    def __init__(self,JOB_NAME,BUILD_ID):
        conf = configparser.ConfigParser()
        conf.read("conf/config.ini")
        # conf.read("../../../conf/config.ini")
        self.JOB_NAME=JOB_NAME
        self.BUILD_ID=str(BUILD_ID)
        self.host = conf.get('ci', 'host')
        self.user = conf.get('ci', 'user')
        self.passwd = conf.get('ci', 'passwd')
        self.database = conf.get('ci', 'database')
        self.Db = DataBaseHandle(self.host, self.user, self.passwd, self.database, 3306)
        self.dtoken=self.get_task_dtoken()

    def get_task_info(self):
        sql="select ci_yapi.case_col,ci_yapi.yapi_url from job_task,ci_yapi where job_task.id=ci_yapi.task_id and job_task.job_name=%s and job_task.status=1"
        args=(self.JOB_NAME)
        data=self.Db.selectDb(sql,args)
        if data[0]==1:
            return data[1]

    def get_task_dtoken(self):
        sql = "select ding_token from job_task where job_name=%s and `status`=1"
        args=(self.JOB_NAME)
        data=self.Db.selectDb(sql,args)
        if data[0]==1:
            return data[1][0][0]

    def run_yapi(self,case_col,url,):
        ret = requests.get(url, )
        path = 'apps/ci/static/html/yapi/' + self.JOB_NAME + "/" + str(self.BUILD_ID) + "/"
        if os.path.exists(path) is False:
            os.makedirs(path)
        path = path + case_col + '.html'
        html = ret.text
        with open(path, 'w',encoding='utf-8') as f:
            f.write(html)
        html = etree.HTML(html)
        len = str(html.xpath('//*[@id="right"]/div[1]/div/text()[1]')[0])

        len=filter(str.isdigit, str(len))
        ret_len=""
        for i in len:
            ret_len+=i

        successNum = html.xpath('//*[@id="right"]/div[1]/div/span/text()')[0]
        successNum = str(successNum).replace(" ","")
        if ret_len=="":
            ret_len=successNum
            failedNum=0
        else:
            failedNum = int(ret_len) - int(successNum)

        return case_col,ret_len, successNum, failedNum

    def write(self,case_col,len, successNum, failedNum,url):
        sql="insert into report (job_name,build_id,`type`,case_col,len,successNum,failedNum,url) values (%s,%s,1,%s,%s,%s,%s,%s)"
        args = (self.JOB_NAME,self.BUILD_ID,case_col,len, successNum, failedNum,url)
        self.Db.insertDB(sql,args)

    def construct(self):
        re = Report()
        data=re.get_report_data(self.JOB_NAME, self.BUILD_ID)
        now_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if data[0]==0:
            pass_rate=0
        else:
            pass_rate=round(data[0]/sum(i[4] for i in data[1]),4)
        pass_rate=str(round((1 - pass_rate) * 100,4)) + '%'
        ret_str="""
构建时间：%s
JOB_NAME：%s
BUILD_ID：%s
通过率：%s
查看详情：http://192.168.2.92/ci/report?job_name=%s&build_id=%s
        """%(now_time,self.JOB_NAME, self.BUILD_ID,pass_rate,self.JOB_NAME,self.BUILD_ID)
        return str(ret_str)


    def run(self):
        task_info=self.get_task_info()
        for i in task_info:
            case_col=i[0]
            url=i[1]
            case_col, len, successNum, failedNum=self.run_yapi(case_col,url)
            url_path='/ci/report/yapi/'+ self.JOB_NAME + "/" + self.BUILD_ID + "/" + case_col + '.html'
            self.write(case_col, len, successNum, failedNum,url_path)
            # if failedNum>0:
            #     send=Send_All()
            #     count="有接口报错，请及时查看,url:http://127.0.0.1:5000/ci/yapi/"+ self.JOB_NAME + "_" + str(self.BUILD_ID) + "_" + case_col + '.html'
            #     send.sending(ding_token,count)
        send=Send_All()
        content=self.construct()
        # content="http://127.0.0.1:5000/ci/report?job_name=%s&build_id=%s"%(self.JOB_NAME,self.BUILD_ID)
        send.sending(self.dtoken,content)


def jenkins_yapi(JOB_NAME,BUILD_ID):
    yapi = Job_yapi(JOB_NAME, BUILD_ID)
    yapi.run()

def jenkins_sonar(JOB_NAME,BUILD_ID):
    url="https://sonar.360che.com/api/measures/search_history?component=transport-qa.360che.com&metrics=sqale_index%2Cduplicated_lines_density%2Cncloc%2Ccoverage%2Cbugs%2Ccode_smells%2Cvulnerabilities&ps=1000"
    ret=requests.get(url)
    bugs=ret.json()['measures'][0]['history'][-1]['value']
    Loophole=ret.json()['measures'][6]['history'][-1]['value']

    return bugs,Loophole

def jenkins_web_ui(JOB_NAME,BUILD_ID):
    pass



def jenkins_run(JOB_NAME,BUILD_ID):
    # path = 'apps/ci/static/html/yapi/test+'+BUILD_ID+'.html'
    # with open(path, 'w',) as f:
    #     f.write("ssdfsfasdf")
    jenkins_yapi(JOB_NAME,BUILD_ID)

    # jenkins_sonar(JOB_NAME,BUILD_ID)
    # jenkins_web_ui(JOB_NAME,BUILD_ID)

if __name__ == '__main__':

    # main()
    # jenkins_yapi_test("qa.kcimg.cn","10")
    # job_name, build_id, `type`, case_col, len, successNum, failedNum, url
    yapi=Job_yapi('shop-api-qa.360che.com',"11")
    # yapi.write("测试集","20","14","6","http://baidu.com")
    yapi.run()

    JOB_NAME = sys.argv[1]
    BUILD_ID=sys.argv[2]
    # task_id = 53
    jenkins_run(JOB_NAME,BUILD_ID)


